package com.mikewoo.nio;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

/**
 * Title: ByteBufferDemo.java
 * Description:  ByteBuffer实例
 * 
 * author     Phantom
 * date       2016年5月19日 下午12:50:42
 * @version    1.0.0
 */
public class ByteBufferDemo {

	public static void readFile(String filename) throws Exception {
		RandomAccessFile randomAccessFile = new RandomAccessFile(filename, "rw");
		FileChannel fileChannel = randomAccessFile.getChannel();
		ByteBuffer bytebuffer = ByteBuffer.allocate(48);
		int size = fileChannel.read(bytebuffer);
		if (size > 0) {
			bytebuffer.flip(); // 转变读写模式
//			while (bytebuffer.hasRemaining()) {
//				System.out.print(bytebuffer.get());
//			}
			Charset charset = Charset.forName("UTF-8");
			System.out.println(charset.newDecoder().decode(bytebuffer).toString());
			
			bytebuffer.clear();
			size = fileChannel.read(bytebuffer);
		}
		fileChannel.close();
		randomAccessFile.close();
	}
}
